package com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_tracker.tracker

import android.annotation.SuppressLint
import android.app.Activity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.bp.hearthealth.pulse.lnapps.R
import com.bp.hearthealth.pulse.lnapps.databinding.BloodPressureFooterLayoutBgBinding
import com.bp.hearthealth.pulse.lnapps.databinding.BloodPressureHeaderLayoutBgBinding
import com.bp.hearthealth.pulse.lnapps.databinding.BloodPressureItemLayoutBgBinding
import com.bp.hearthealth.pulse.lnapps.bp_db.bp_bloodpressure.BloodPressure
import com.bp.hearthealth.pulse.lnapps.bp_db.bp_bloodpressure.BloodPressureData
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_extension.UIHelperBp
import com.bp.hearthealth.pulse.lnapps.bp_model.BarChartBeanBp
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_dialog.CalendarDialog
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_tracker.blood_pressure.BloodPressureViewModel
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_tracker.bp_bean.BpBloodPressureAverageValues
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_tracker.bp_bean.BpBloodPressureFilter
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bp.hearthealth.pulse.lnapps.bp_utils.DateUtils
import com.bp.hearthealth.pulse.lnapps.databinding.BloodPressureHeaderSortLayoutBgBinding
import com.isnoam.calendar.bean.DateInfo


class BpTrackerBloodPressureAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private lateinit var headerItemVH: HeaderItemVH
    private lateinit var filterMap: Map<BpBloodPressureFilter, BpBloodPressureAverageValues>
    private lateinit var adapterClickListener: BpTrackerAdapterClickListener
    private lateinit var activity: Activity
    private lateinit var viewModel: BloodPressureViewModel
    private var dataList: List<BloodPressureData> = ArrayList()
    private var list: MutableList<BloodPressure> = mutableListOf()
    private var stateType: List<Int> = ArrayList()
    private val data = intArrayOf(0, 0, 0, 0, 0, 0) // 每个类型的数据
    private var chooseOne = false//true:选择某一天, false:选择时间范围

    private val pagerList = mutableListOf(
        BpBloodPressureFilter.mapToString(BpBloodPressureFilter.MAX_DATA),
        BpBloodPressureFilter.mapToString(BpBloodPressureFilter.MIN_DATA),
        BpBloodPressureFilter.mapToString(BpBloodPressureFilter.LATEST_DATA),
        BpBloodPressureFilter.mapToString(BpBloodPressureFilter.LATEST_24_HOURE_DATA),
        BpBloodPressureFilter.mapToString(BpBloodPressureFilter.AVERAGE_DATA)
    )

    companion object {
        private const val TYPE_HEADER = 0
        private const val TYPE_FIVE_VIEW = 1
        private const val TYPE_ITEM = 2
        private const val TYPE_FOOTER = 3
    }

    private var headerView: View? = null
    private var headerFiveView: View? = null
    private var footerView: View? = null
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            TYPE_FIVE_VIEW -> {
                FiveCategoriesItemVH(
                    BloodPressureHeaderSortLayoutBgBinding.inflate(
                        LayoutInflater.from(parent.context), parent, false
                    )
                )
            }

            TYPE_HEADER -> {
                headerItemVH = HeaderItemVH(
                    BloodPressureHeaderLayoutBgBinding.inflate(
                        LayoutInflater.from(parent.context), parent, false
                    )
                )
                headerItemVH
            }

            TYPE_ITEM -> {
                ItemVH(
                    BloodPressureItemLayoutBgBinding.inflate(
                        LayoutInflater.from(parent.context), parent, false
                    )
                )
            }

            TYPE_FOOTER -> {
                val footerVH = FooterVH(
                    BloodPressureFooterLayoutBgBinding.inflate(
                        LayoutInflater.from(parent.context), parent, false
                    )
                )
                footerVH
            }

            else -> throw IllegalArgumentException("Invalid view type")
        }
    }

    fun setHeaderView(view: View) {
        headerView = view
        notifyItemInserted(1)
    }

    fun setHeaderFiveView(view: View) {
        headerFiveView = view
        notifyItemInserted(0)
    }

    fun setFooterView(view: View) {
        footerView = view
        if (headerView != null) {
            notifyItemInserted(dataList.size + 1)
        } else {
            notifyItemInserted(dataList.size)
        }
    }

    override fun getItemViewType(position: Int): Int {
        return when {
            position == 0 && headerFiveView != null -> TYPE_FIVE_VIEW
            position == 1 && headerView != null -> TYPE_HEADER
            position == itemCount - 1 && footerView != null -> TYPE_FOOTER
            else -> TYPE_ITEM
        }
    }

    override fun getItemCount(): Int {
        var count = dataList.size
        if (headerFiveView != null) count++
        if (headerView != null) count++
        if (footerView != null) count++
        return count
    }

    //全部数据内的前三条
    private fun getRecentBloodPressureData(bloodPressureList: List<BloodPressure>): List<BloodPressureData> {
        val recentData = mutableListOf<BloodPressureData>()
        var remaining = 3 // 剩余需要获取的条目数
        for (bloodPressure in bloodPressureList) {
            // 对 bloodPressureList 进行排序，按时间戳降序排列
            val sortedList = bloodPressure.bloodPressureList.sortedByDescending { it.timePeriod }
            // 获取最近的数据，最多取剩余需要获取的条目数
            val recent = sortedList.take(remaining)
            recentData.addAll(recent)
            remaining -= recent.size
            // 如果剩余需要获取的条目数为0，即已经取到了3条数据，则退出循环
            if (remaining == 0) {
                break
            }
        }
        return recentData
    }

    override fun onBindViewHolder(
        holder: RecyclerView.ViewHolder,
        @SuppressLint("RecyclerView") position: Int,
    ) {
        when (holder) {
            is FiveCategoriesItemVH -> holder.bindHeaderData()
            is HeaderItemVH -> holder.bindHeaderData()
            is ItemVH -> {
                val itemPosition = if (headerFiveView != null) {
                    position - 2
                } else if (headerView != null) {
                    position - 1
                } else {
                    position
                }
                holder.bindData(dataList[itemPosition])
                holder.itemView.setOnClickListener {
                    adapterClickListener.onItemClick(
                        dataList[itemPosition].id, dataList[itemPosition].date
                    )
                }
            }

            is FooterVH -> {
                holder.bindData()
            }
        }
    }

    fun setOnAdapterClickListener(clickListener: BpTrackerAdapterClickListener) {
        this.adapterClickListener = clickListener
    }

    fun setActivity(activity: Activity, viewModel: BloodPressureViewModel) {
        this.activity = activity
        this.viewModel = viewModel
    }

    //视图数据
    fun setViewListData(list: List<BloodPressure>) {
        this.list = list.toMutableList()
        notifyItemChanged(1)
    }

    //3条历史激励
    fun setDataThreeList(list: List<BloodPressureData>) {
//        val diffCallback = BloodPressureDiffCallback(dataList, list)
//        val diffResult = DiffUtil.calculateDiff(diffCallback)
        dataList = list
        notifyDataSetChanged()
//        diffResult.dispatchUpdatesTo(this)
    }

    //5种类型筛选
    fun setFilterMapValue(map: Map<BpBloodPressureFilter, BpBloodPressureAverageValues>) {
        this.filterMap = map
        notifyItemChanged(0)
    }

    //Statistics
    fun setStatisticsCount(response: List<Int>) {
        this.stateType = response
        notifyItemChanged(itemCount - 1)
    }

    inner class ItemVH(val binding: BloodPressureItemLayoutBgBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bindData(item: BloodPressureData) {
            binding.tvPulse.text = "${UIHelperBp.getString(R.string._pulse_str)}: ${(item.pulse)} ${
                UIHelperBp.getString(R.string._bpm_str)
            }"
            binding.bean = item
        }
    }

    inner class FooterVH(val binding: BloodPressureFooterLayoutBgBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bindData() {
            binding.includeArticle.apply {
                firstText = UIHelperBp.getString(R.string._healthy_diet_tips_1_str)
                secondText = UIHelperBp.getString(R.string._healthy_diet_tips_6_str)
                thirdText = UIHelperBp.getString(R.string._healthy_diet_tips_2_str)
//                firstUrl = Constants.HD_URL1
//                secondUrl = Constants.HD_URL2
//                thirdUrl = Constants.HD_URL3
                ivArticleFirst.setOnClickListener {
                    adapterClickListener.articleItemClick(
                        firstText.toString(), R.mipmap.hd_1
                    )
                }

                ivArticleSecond.setOnClickListener {
                    adapterClickListener.articleItemClick(
                        secondText.toString(), R.mipmap.hd_2
                    )
                }

                ivArticleThird.setOnClickListener {
                    adapterClickListener.articleItemClick(
                        thirdText.toString(), R.mipmap.hd_3
                    )
                }
            }
            binding.tvHistory.setOnClickListener { adapterClickListener.onHistoryClick() }
            val countMap = stateType.groupingBy { it }.eachCount()
            countMap.forEach { (status, count) ->
                data[status] = count
                LogUtil.i("Status $status: $count")
            }
            binding.stateType = stateType.size
            binding.colorRingView.setData(data)
        }
    }

    inner class FiveCategoriesItemVH(val binding: BloodPressureHeaderSortLayoutBgBinding) :
        RecyclerView.ViewHolder(binding.root) {

        private var calendarDialog: CalendarDialog? = null
        private var adapter: BpViewPagerTextAdapter? = null

        fun bindHeaderData() {
            binding.viewModel = viewModel
            initViewPager()
            initCalendarDialog()
        }

        private fun initViewPager() {
            if (adapter == null) {
                adapter = BpViewPagerTextAdapter(pagerList)
            }
            binding.apply {
                viewPager.adapter = adapter
                viewPager.isUserInputEnabled = false
                viewPager.orientation = ViewPager2.ORIENTATION_HORIZONTAL
                viewChangeLeft.setOnClickListener {
                    if (viewPager.currentItem != 0) {
                        viewPager.currentItem = viewPager.currentItem - 1
                    }
                }
                viewChangeRight.setOnClickListener {
                    if (viewPager.currentItem != pagerList.size - 1) {
                        viewPager.currentItem = viewPager.currentItem + 1
                    }
                }
                if (!this@BpTrackerBloodPressureAdapter::filterMap.isInitialized) {
                    return
                }
                viewPager.registerOnPageChangeCallback(object : OnPageChangeCallback() {
                    override fun onPageSelected(position: Int) {
                        when (pagerList[position]) {
                            BpBloodPressureFilter.mapToString(BpBloodPressureFilter.LATEST_DATA) -> {
                                filterBean = filterMap[BpBloodPressureFilter.LATEST_DATA]
                            }

                            BpBloodPressureFilter.mapToString(BpBloodPressureFilter.LATEST_24_HOURE_DATA) -> {
                                filterBean = filterMap[BpBloodPressureFilter.LATEST_24_HOURE_DATA]
                            }

                            BpBloodPressureFilter.mapToString(BpBloodPressureFilter.AVERAGE_DATA) -> {
                                filterBean = filterMap[BpBloodPressureFilter.AVERAGE_DATA]
                            }

                            BpBloodPressureFilter.mapToString(BpBloodPressureFilter.MAX_DATA) -> {
                                filterBean = filterMap[BpBloodPressureFilter.MAX_DATA]
                            }

                            else -> {
                                filterBean = filterMap[BpBloodPressureFilter.MIN_DATA]
                            }
                        }
                    }
                })
                binding.viewPager.currentItem = 2
            }
        }

        private fun initCalendarDialog() {
            binding.llTime.setOnClickListener { calendarDialog!!.showDialog() }
            calendarDialog = CalendarDialog(activity)
            calendarDialog!!.setOnBtnClickLisener(object :
                CalendarDialog.OnDateRangeSelectedListener {
                override fun setOnDateRangeSelectedListener(
                    startDate: DateInfo, endDate: DateInfo?
                ) {
//                    adapterClickListener.timeClick(startDate,endDate)
                    if (endDate == null) {
                        chooseOne = true
//                        viewModel.selectedTime.value = startDate.formatAsMMMdd()
                        viewModel.selectedTime.set(startDate.formatAsMMMdd())
                        //选择某一天
                        viewModel.startTime.value = startDate.timeInMillis()
                        //获取当天开始时间和结束时间
                        viewModel.startTime.value =
                            DateUtils.getStartAndEndOfDay(startDate.timeInMillis()).first
                        viewModel.endTime.value =
                            DateUtils.getStartAndEndOfDay(startDate.timeInMillis()).second
                        LogUtil.i("查询时间戳为：开始时间：${viewModel.startTime.value} 结束时间：${viewModel.endTime.value}")
                    } else {
                        chooseOne = false
                        //选择的是范围
                        viewModel.selectedTime.set("${startDate.formatAsMMMdd()}-${endDate.formatAsMMMdd()}")
//                        viewModel.selectedTime.value =
//                            "${startDate.formatAsMMMdd()}-${endDate.formatAsMMMdd()}"
                        //开始当天的00:00:00时间戳
                        viewModel.startTime.value =
                            DateUtils.getStartAndEndOfDay(startDate.timeInMillis()).first
                        //结束当天的23:59:59时间戳
                        viewModel.endTime.value =
                            DateUtils.getStartAndEndOfDay(endDate.timeInMillis()).second
                        LogUtil.i("查询时间戳为：开始时间：${startDate.timeInMillis()} 结束时间：${endDate.timeInMillis()}")
                    }
                    viewModel.getBloodPressureDataForDateRange(Constants.USER_ID)
                }
            })
        }
    }


    inner class HeaderItemVH(val binding: BloodPressureHeaderLayoutBgBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bindHeaderData() {
            initBarData()
        }


        private fun initBarData() {
            val yBarList: MutableList<BarChartBeanBp> = ArrayList()
            val xAxisList: MutableList<String> = ArrayList()
            if (list.isNotEmpty()) {
                if (chooseOne) {
                    //某一天的数据
                    if (list.first().bloodPressureList.isEmpty()) {
                        return
                    }
                    if (list.first().bloodPressureList.isNotEmpty()) {
                        val todayList = list.first().bloodPressureList
                        for (index in todayList.indices) {
                            yBarList.add(
                                BarChartBeanBp(
                                    todayList[index].systolic.toInt(),
                                    todayList[index].diastolic.toInt()
                                )
                            )
                            xAxisList.add(DateUtils.getDateAndHourHm(todayList[index].timePeriod))
                        }
                    }
                } else {
                    //多天的数据，取每个bloodPressureList中的第一条
                    for (index in list.indices) {
                        if (list[index].bloodPressureList.isEmpty()) {
                            return
                        }
                        if (list[index].bloodPressureList.isNotEmpty()) {
                            val moreFirstData = list[index].bloodPressureList.first()
                            yBarList.add(
                                BarChartBeanBp(
                                    moreFirstData.systolic.toInt(), moreFirstData.diastolic.toInt()
                                )
                            )
                            xAxisList.add(DateUtils.getDateAndMD(moreFirstData.timePeriod))
                        }
                    }
                }
            }
            binding.chartView.setChartData(xAxisList, yBarList)
        }
    }
}